package yc.web.servlets;

import yc.web.model.JsonModel;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@WebServlet("/FileToOSSText.action")
@MultipartConfig(fileSizeThreshold = 1024*1024 , maxFileSize = 1024*1024*5 , maxRequestSize = 1024*1024*5*5)
public class FileToOSSText extends BaseServlet {

    public void regFile(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        JsonModel jm = new JsonModel();
        Collection<Part> parts = req.getParts(); // 获取所有部分
        System.out.println("getParts:"+req.getParts());
        try {
            for (Part part : parts) {
                if (part.getContentType() != null) { // 检查部分是否为文件
                    String fileName = part.getSubmittedFileName(); // 获取文件名
                    InputStream fileContent = part.getInputStream(); // 获取文件内容的输入流
                    String url = UploadToOSS.uploadFileOSS( fileName ,  fileContent );//调用上传到OSS的函数
                    if ( "0".equals( url ) ){  //上传失败
                        jm.setCode(0);
                        jm.setError("上传失败。。。");
                        super.writeJson( jm , resp );
                        return;
                    }else {     //上传成功
                        jm.setObj( url );//访问域名
                        jm.setCode(1); //表示成功
                    }
                }
            }
        } catch (Exception ex) {
            throw new ServletException(ex);
        } finally {
            super.writeJson(jm,resp);
            System.out.println("OSS close Success");
            UploadToOSS.close(); // 最终，无论上传成功还是失败，都关闭OSS客户端实例以释放资源。
        }
    }
}
